package com.hksj.drcs.service.impl;

import com.hksj.drcs.mapper.DrcsCockpitMapper;
import com.hksj.drcs.query.CockpitQuery;
import com.hksj.drcs.service.DrcsCockpitService;
import com.hksj.drcs.vo.ControlDeviceNumVO;
import com.hksj.drcs.vo.ControlDeviceOverviewVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zengke
 * @version 1.0
 * @see DrcsCockpitServiceImpl
 * @since 2025/06/05 18:11
 */

@Service(value = "drcsCockpitServiceImpl")
public class DrcsCockpitServiceImpl implements DrcsCockpitService {

    @Autowired
    private DrcsCockpitMapper drcsCockpitMapper;

    @Value("${hk.remote.control.ip:''}")
    private String ip;

    @Value("${hk.remote.control.port:''}")
    private String port;

    /**
     * 查询控制设备概览列表
     *
     * @param query 驾驶舱查询条件
     * @return 控制设备数量概览列表
     */
    @Override
    public List<ControlDeviceOverviewVO> queryControlDeviceOverview(CockpitQuery query) {

        //参数校验
        Assert.notEmpty(query.getLoopTypeList(),"回路类型列表不能为空");

        Assert.notEmpty(query.getSpecialityCodeList(),"专业代码列表不能为空");

        Assert.notEmpty(query.getProductClassifiedCodeList(),"产品类型代码列表不能为空");

        //查询设备详情列表
        List<ControlDeviceOverviewVO.ControlDeviceDetailVO> deviceDetailList = drcsCockpitMapper.queryControlDeviceDetailList(query);

        //设备详情列表以回路类型进行分组得到设备详情集合
        Map<Integer, List<ControlDeviceOverviewVO.ControlDeviceDetailVO>> deviceDetailMap = deviceDetailList.stream().collect(Collectors.groupingBy(ControlDeviceOverviewVO.ControlDeviceDetailVO::getLoopType));

        //将前端传的回路类型列表转换为控制设备概览列表
        List<ControlDeviceOverviewVO> newControlDeviceOverviewList = query.getLoopTypeList().stream().map(loopType -> {

            //创建设备概览对象
            ControlDeviceOverviewVO controlDeviceOverviewVO = new ControlDeviceOverviewVO();

            //设置回路类型
            controlDeviceOverviewVO.setLoopType(loopType);

            //设备详情集合不为空、设置回路类型对应的设备详情列表
            if (!ObjectUtils.isEmpty(deviceDetailMap)) {
                controlDeviceOverviewVO.setDeviceList(deviceDetailMap.get(loopType));
            }

            return controlDeviceOverviewVO;
        }).collect(Collectors.toList());

        //返回设备概览对象
        return newControlDeviceOverviewList;
    }

    /**
     * 查询控制设备数量
     *
     * @param query 驾驶舱查询条件
     * @return 控制设备数量
     */
    @Override
    public List<ControlDeviceNumVO> queryControlDeviceNumList(CockpitQuery query) {

        //参数校验
        Assert.notEmpty(query.getLoopTypeList(),"回路类型列表不能为空");

        Assert.notEmpty(query.getSpecialityCodeList(),"专业代码列表不能为空");

        Assert.notEmpty(query.getProductClassifiedCodeList(),"产品类型代码列表不能为空");

        //查询控制设备数量列表
        List<ControlDeviceNumVO> controlDeviceNumList = drcsCockpitMapper.queryControlDeviceNumList(query);

        //根据回路类型进行分组
        Map<Integer, ControlDeviceNumVO> controlDeviceNumMap = controlDeviceNumList.stream().collect(Collectors.toMap(ControlDeviceNumVO::getLoopType, Function.identity()));

        //将传来的回路类型转换为控制设备数量列表并设置对应值
        List<ControlDeviceNumVO> newControlDeviceNumList = query.getLoopTypeList().stream().map(loopType -> {

            //创建设备数量对象
            ControlDeviceNumVO controlDeviceNumVO = new ControlDeviceNumVO();

            //设置回路类型
            controlDeviceNumVO.setLoopType(loopType);

            //设置回路类型对应的设备数量
            if (!ObjectUtils.isEmpty(controlDeviceNumMap)) {

                ControlDeviceNumVO controlDeviceNumFromDB = controlDeviceNumMap.get(loopType);

                //判断从数据库查询的设备数量对象是否为空
                if (!ObjectUtils.isEmpty(controlDeviceNumFromDB)) {

                    //不为空、设置设备数量
                    controlDeviceNumVO.setDeviceNum(controlDeviceNumFromDB.getDeviceNum());
                }

            }
            return controlDeviceNumVO;
        }).collect(Collectors.toList());

        //返回设置好的设备数量列表
        return newControlDeviceNumList;
    }

    /**
     * 远程控制设备
     *
     * @param deviceId   网关设备id
     * @param functionId 网关设备对应的功能id
     * @param properties 属性及属性值的Map集合
     * @return 控制结果
     */
    @Override
    public String control(String deviceId, String functionId, Map<String, Object> properties) {

        // 1. 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();

        // 2. 设置 URL（路径变量）
        String url = "http://{ip}:{port}/device/invoked/{deviceId}/function/{functionId}/remote/{remoteIpAddress}".replace("{ip}", ip).replace("{port}", port).replace("{deviceId}", deviceId).replace("{functionId}", functionId);

        // 3. 构建请求头（可选，如 Content-Type）
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 5. 构建请求实体（包含 headers + body）
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(properties, headers);

        // 6. 构造路径变量
        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("deviceId", "deviceId");
        uriVariables.put("functionId", "functionId");
        uriVariables.put("remoteIpAddress",ip);

        try {
            // 7. 发起请求并获取响应
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class, uriVariables);

            HttpStatus statusCode = responseEntity.getStatusCode();

            if (statusCode == HttpStatus.OK){
                return "控制成功";
            } else {
                throw new RuntimeException("控制失败");
            }

        } catch (Exception e){

            throw new RuntimeException(e.getMessage());
        }
    }
}
